<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑测试用例"
    width="85%"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="edit-form"
      style="max-height: 65vh; overflow-y: auto"
    >
      <!-- 测试用例基本信息卡片 -->
      <el-card class="form-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>测试用例基本信息</span>
          </div>
        </template>
        <div class="form-row">
          <el-form-item label="需求名称" prop="name" class="form-item">
            <el-input v-model="form.name" maxlength="200" show-word-limit />
          </el-form-item>
          <el-form-item label="迭代版本" class="form-item">
            <el-input
              v-model="form.demandInfo.iterativeVersion"
              maxlength="50"
            />
          </el-form-item>
        </div>
      </el-card>

      <!-- 需求任务列表卡片 -->
      <el-card class="form-card task-list-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>需求任务列表</span>
            <el-button
              type="primary"
              size="small"
              @click="addNewDemand"
              class="add-task-btn"
            >
              <el-icon><Plus /></el-icon> 添加任务
            </el-button>
          </div>
        </template>

        <div
          v-if="
            !form.demandInfo ||
            Object.keys(form.demandInfo).filter((key) =>
              key.startsWith('demand_')
            ).length === 0
          "
          class="empty-tasks"
        >
          <el-empty description="暂无任务，请添加" />
        </div>

        <transition-group name="task-list" tag="div" class="task-list">
          <el-card
            v-for="(item, key, index) in demandItems"
            :key="key"
            class="task-item"
            shadow="hover"
          >
            <template #header>
              <div class="task-header">
                <el-tag size="medium" effect="dark" class="task-number"
                  >任务 #{{ index + 1 }}</el-tag
                >
                <el-button
                  type="danger"
                  size="small"
                  circle
                  plain
                  @click="removeDemand(key)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>

            <div class="task-content">
              <div class="task-form-row">
                <el-form-item label="任务名称" class="task-form-item-full">
                  <el-input
                    v-model="item.demandName"
                    placeholder="请输入任务名称"
                    maxlength="100"
                  />
                </el-form-item>
              </div>

              <div class="task-form-row">
                <el-form-item label="需求描述" class="task-form-item-full">
                  <el-input
                    v-model="item.demandDescription"
                    placeholder="请输入需求描述"
                    type="textarea"
                    :rows="2"
                  />
                </el-form-item>
              </div>

              <div class="task-form-row four-columns">
                <el-form-item label="难度" class="task-form-item-equal">
                  <el-select
                    v-model="item.difficulty"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option label="简单" value="简单" />
                    <el-option label="中等" value="中等" />
                    <el-option label="复杂" value="复杂" />
                    <el-option label="高" value="高" />
                  </el-select>
                </el-form-item>
                <el-form-item label="预计时间" class="task-form-item-equal">
                  <div class="time-input-with-unit">
                    <el-input-number
                      v-model="item.expectedTime"
                      :min="0.5"
                      :max="20"
                      :step="0.5"
                      placeholder="天"
                      style="width: 100%"
                    />
                    <span class="time-unit">天</span>
                  </div>
                </el-form-item>
                <el-form-item label="时间范围" class="task-form-item-equal">
                  <el-date-picker
                    v-model="item.timeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                    @change="(val) => handleDateRangeChange(item, val)"
                  />
                </el-form-item>
                <el-form-item label="测试人员" class="task-form-item-equal">
                  <el-select
                    v-model="item.assignedTester"
                    placeholder="请选择测试人员"
                    style="width: 100%"
                    filterable
                  >
                    <el-option
                      v-for="tester in testCaseTesters"
                      :key="tester.name"
                      :label="tester.name"
                      :value="tester.name"
                    >
                      <div class="developer-option">
                        <span>{{ tester.name }}</span>
                        <div class="tags">
                          <!-- 负责模块：绿色 -->
                          <div class="tag-group">
                            <el-tag
                              v-for="(skill, index) in tester.expertise"
                              :key="'skill-' + index"
                              size="small"
                              type="success"
                            >
                              {{ skill }}
                            </el-tag>
                          </div>

                          <!-- 技术栈：红色 -->
                          <div
                            class="tag-group"
                            v-if="
                              tester.technologyStack &&
                              tester.technologyStack.length > 0
                            "
                          >
                            <el-tag
                              v-for="(tech, index) in tester.technologyStack"
                              :key="'tech-' + index"
                              size="small"
                              type="danger"
                            >
                              {{ tech }}
                            </el-tag>
                          </div>

                          <!-- 能力等级：蓝色 -->
                          <div class="tag-group" v-if="tester.level">
                            <el-tag size="small" type="primary">
                              {{ tester.level }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>

              <!-- 测试用例列表 -->
              <div class="task-form-row">
                <el-form-item label="测试用例" class="task-form-item-full">
                  <div class="test-cases-container">
                    <div
                      v-if="
                        !item.testCaseList || item.testCaseList.length === 0
                      "
                      class="empty-test-cases"
                    >
                      <span class="empty-text">暂无测试用例</span>
                      <el-button
                        type="primary"
                        size="small"
                        @click="addTestCase(item)"
                        >添加测试用例</el-button
                      >
                    </div>
                    <div v-else>
                      <el-table
                        :data="item.testCaseList"
                        border
                        size="small"
                        class="test-cases-table"
                      >
                        <el-table-column
                          prop="demandName"
                          label="编号"
                          width="80"
                        />
                        <el-table-column label="测试步骤" min-width="180">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.description"
                              type="textarea"
                              :rows="2"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column label="预期结果" min-width="180">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.preconditions"
                              type="textarea"
                              :rows="2"
                            />
                          </template>
                        </el-table-column>
                      </el-table>
                      <div class="add-test-case-btn">
                        <el-button
                          type="primary"
                          size="small"
                          @click="addTestCase(item)"
                        >
                          <el-icon><Plus /></el-icon> 添加测试用例
                        </el-button>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-card>
        </transition-group>
      </el-card>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch, computed } from "vue";
import { Delete, Plus, Edit } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { testCase } from "@/utils/cueWords";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  testCaseData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "save"]);

const dialogVisible = ref(false);
const formRef = ref(null);

// 表单默认值
const defaultForm = {
  name: "",
  code: "",
  status: "已分配",
  createTime: new Date().toISOString().split("T")[0],
  testCaseInfo: {
    demandName: "",
    description: "",
    version: "1.0",
    assignedTester: "",
    priority: "P2",
    type: "功能测试",
  },
  demandInfo: {
    iterativeVersion: "1.0",
    testDeveloper: {
      name: "",
      expertise: [],
    },
  },
  testCaseList: [],
};

const form = reactive({ ...defaultForm });

// 测试人员数据
const testCaseTesters = ref([]);

// 计算属性：获取所有demand_开头的属性
const demandItems = computed(() => {
  if (!form.demandInfo) return {};

  const items = {};
  for (const key in form.demandInfo) {
    if (key.startsWith("demand_")) {
      items[key] = form.demandInfo[key];

      // 确保每个demand都有timeRange属性
      if (items[key].startTime && items[key].endTime && !items[key].timeRange) {
        items[key].timeRange = [items[key].startTime, items[key].endTime];
      }

      // 确保每个demand都有testCaseList属性
      if (!items[key].testCaseList) {
        items[key].testCaseList = [];
      }
    }
  }
  return items;
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入需求名称", trigger: "blur" },
    { min: 2, max: 100, message: "长度在 2 到 100 个字符", trigger: "blur" },
  ],
  code: [{ required: true, message: "请输入测试用例编号", trigger: "blur" }],
};

// 监听对话框显示状态
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if (val && props.testCaseData) {
      // 深拷贝任务数据到表单
      const taskCopy = JSON.parse(JSON.stringify(props.testCaseData));

      // 确保必要字段存在
      if (!taskCopy.testCaseInfo) {
        taskCopy.testCaseInfo = { ...defaultForm.testCaseInfo };
      }

      if (!taskCopy.demandInfo) {
        taskCopy.demandInfo = { ...defaultForm.demandInfo };
      }

      // 确保每个demand都有timeRange属性、expectedTime属性和assignedTester属性
      for (const key in taskCopy.demandInfo) {
        if (key.startsWith("demand_")) {
          const demand = taskCopy.demandInfo[key];
          if (demand.startTime && demand.endTime && !demand.timeRange) {
            demand.timeRange = [demand.startTime, demand.endTime];
          }

          // 确保expectedTime是数字类型
          if (demand.expectedTime !== undefined) {
            if (typeof demand.expectedTime === "string") {
              // 尝试将字符串转换为数字
              demand.expectedTime = parseFloat(demand.expectedTime) || 3;
            } else if (typeof demand.expectedTime !== "number") {
              demand.expectedTime = 3; // 默认值
            }
          } else {
            demand.expectedTime = 3; // 如果不存在，设置默认值
          }

          // 确保每个demand都有assignedTester属性
          if (!demand.assignedTester) {
            // 如果任务没有特定的测试人员，则使用全局测试人员
            demand.assignedTester = taskCopy.testCaseInfo?.assignedTester || "";
          }

          // 确保每个测试用例都有需要的属性
          if (demand.testCaseList && demand.testCaseList.length > 0) {
            demand.testCaseList.forEach((testCase) => {
              if (!testCase.assignedTester) {
                testCase.assignedTester =
                  demand.assignedTester ||
                  taskCopy.testCaseInfo?.assignedTester ||
                  "";
              }
            });
          }
        }
      }

      // 更新表单数据
      Object.assign(form, taskCopy);

      // 从cueWords.js获取测试人员数据
      try {
        // 解析testCase字符串为JSON对象
        const testCaseData = JSON.parse(testCase);
        if (testCaseData && testCaseData.developers) {
          // 转换格式
          testCaseTesters.value = testCaseData.developers.map((dev) => ({
            name: dev.name,
            expertise: dev.skills || [],
            technologyStack: dev.technologyStack || [],
            level: dev.level || "普通",
          }));
        }
      } catch (error) {
        console.error("解析测试人员数据失败:", error);
        // 兜底测试人员数据
        testCaseTesters.value = [
          {
            name: "崔艳",
            expertise: ["告警详情", "告警列表"],
            technologyStack: ["sql", "测试"],
            level: "高级",
          },
          {
            name: "李元奇",
            expertise: ["视频管理", "AR大屏", "播放器"],
            technologyStack: ["sql", "测试"],
            level: "高级",
          },
        ];
      }
    }
  }
);

// 监听对话框状态，同步到父组件
watch(
  () => dialogVisible.value,
  (val) => {
    emit("update:modelValue", val);
  }
);

// 添加新需求
const addNewDemand = () => {
  // 找到最大的demand_索引
  let maxIndex = 0;
  for (const key in form.demandInfo) {
    if (key.startsWith("demand_")) {
      const index = parseInt(key.split("_")[1]);
      if (index > maxIndex) {
        maxIndex = index;
      }
    }
  }

  // 创建新的demand_key
  const newKey = `demand_${maxIndex + 1}`;

  // 确保demandInfo存在
  if (!form.demandInfo) {
    form.demandInfo = {};
  }

  // 添加新需求
  form.demandInfo[newKey] = {
    demandName: "",
    demandDescription: "",
    difficulty: "中等",
    expectedTime: 3,
    startTime: "",
    endTime: "",
    timeRange: [],
    testCaseList: [],
    assignedTester: "",
  };
};

// 移除需求
const removeDemand = (key) => {
  if (form.demandInfo && form.demandInfo[key]) {
    delete form.demandInfo[key];
  }
};

// 处理日期范围变化
const handleDateRangeChange = (demand, val) => {
  if (val && val.length === 2) {
    [demand.startTime, demand.endTime] = val;
  } else {
    demand.startTime = "";
    demand.endTime = "";
  }
};

// 添加测试用例
const addTestCase = (demand) => {
  if (!demand.testCaseList) {
    demand.testCaseList = [];
  }

  // 生成新的测试用例ID
  const newId = `TC${demand.testCaseList.length + 1}`.padStart(3, "0");

  demand.testCaseList.push({
    demandName: newId,
    description: "",
    preconditions: "",
  });
};

// 编辑测试用例
const editTestCase = (demand, testCase, index) => {
  // 这里可以实现编辑测试用例的逻辑，例如打开一个编辑对话框
  ElMessage.info(`编辑测试用例 ${testCase.demandName}`);
};

// 移除测试用例
const removeTestCase = (demand, index) => {
  if (demand.testCaseList && index >= 0 && index < demand.testCaseList.length) {
    demand.testCaseList.splice(index, 1);
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 验证表单
  await formRef.value.validate((valid) => {
    if (valid) {
      // 处理提交前的数据整理
      const formData = JSON.parse(JSON.stringify(form));

      // 更新测试用例列表
      formData.testCaseList = [];

      // 从各个demand中收集测试用例
      for (const key in formData.demandInfo) {
        if (key.startsWith("demand_")) {
          const demand = formData.demandInfo[key];
          if (demand.testCaseList && demand.testCaseList.length > 0) {
            // 为每个测试用例添加demand相关信息
            demand.testCaseList.forEach((testCase, index) => {
              formData.testCaseList.push({
                id: `${key.split("_")[1]}-${index + 1}`,
                demandName: demand.demandName,
                description: testCase.description,
                preconditions: testCase.preconditions,
                difficulty: demand.difficulty,
                expectedTime: demand.expectedTime,
                startTime: demand.startTime,
                endTime: demand.endTime,
                assignedTester:
                  demand.assignedTester ||
                  formData.testCaseInfo.assignedTester ||
                  "",
                // 确保测试人员信息同步到测试用例的testCaseInfo中
                testCaseInfo: {
                  ...(testCase.testCaseInfo || {}),
                  assignedTester:
                    demand.assignedTester ||
                    formData.testCaseInfo.assignedTester ||
                    "",
                  priority:
                    demand.difficulty || formData.testCaseInfo.priority || "P2",
                  version:
                    formData.demandInfo.iterativeVersion ||
                    formData.testCaseInfo.version ||
                    "1.0",
                },
              });
            });
          }
        }
      }

      // 确保全局测试用例信息也包含测试人员信息
      if (formData.testCaseInfo) {
        // 如果有任何任务指定了测试人员，使用第一个找到的有效值
        const firstAssignedTester = Object.values(formData.demandInfo)
          .filter((item) => typeof item === "object" && item.assignedTester)
          .map((item) => item.assignedTester)
          .find(Boolean);

        if (firstAssignedTester && !formData.testCaseInfo.assignedTester) {
          formData.testCaseInfo.assignedTester = firstAssignedTester;
        }
      }

      emit("save", formData);
      dialogVisible.value = false;
    } else {
      ElMessage.error("请完善表单信息");
      return false;
    }
  });
};

// 对话框关闭时重置表单
const handleClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
</script>

<style scoped lang="scss">
.edit-form {
  .form-card {
    margin-bottom: 16px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      font-size: 16px;
    }

    .form-row {
      display: flex;
      gap: 20px;
      margin-bottom: 16px;

      .form-item {
        flex: 1;
      }
    }
  }

  .task-list-card {
    .add-task-btn {
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .empty-tasks {
      padding: 30px 0;
    }

    .task-list {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .task-item {
      margin-bottom: 16px;
      border-left: 3px solid var(--el-color-primary);
      overflow: hidden;

      .task-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .task-number {
          font-weight: bold;
        }
      }

      .task-content {
        padding: 5px;

        .task-form-row {
          display: flex;
          gap: 16px;
          margin-bottom: 12px;
          width: 100%;

          &.four-columns {
            .task-form-item-equal {
              flex: 1;
              min-width: 0;

              :deep(.el-form-item__content) {
                width: 100%;
                display: flex;

                .el-select,
                .el-date-editor,
                .time-input-with-unit {
                  width: 100% !important;
                  flex: 1;
                }
              }
            }
          }

          &.three-columns {
            .task-form-item-equal {
              flex: 1;
              min-width: 0;

              :deep(.el-form-item__content) {
                width: 100%;
                display: flex;

                .el-select,
                .el-date-editor,
                .time-input-with-unit {
                  width: 100% !important;
                  flex: 1;
                }
              }
            }
          }

          &.two-columns {
            .task-form-item-equal {
              flex: 1;
              min-width: 0;

              .selected-expertise {
                display: flex;
                flex-wrap: wrap;
                gap: 4px;
                margin-top: 5px;

                .expertise-tag {
                  margin: 0;
                }
              }
            }
          }

          .task-form-item-full {
            flex: 1;
            width: 100%;

            :deep(.el-form-item__content) {
              width: 100%;
            }
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.time-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;

  :deep(.el-input-number) {
    width: 100%;
  }

  .time-unit {
    margin-left: 5px;
    color: #606266;
    white-space: nowrap;
    font-size: 14px;
  }
}

.developer-option {
  display: flex;
  flex-direction: column;
  gap: 5px;

  .tags {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .tag-group {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      margin-bottom: 2px;
    }
  }
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100% !important;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

// 测试用例相关样式
.test-cases-container {
  width: 100%;

  .empty-test-cases {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
    gap: 10px;

    .empty-text {
      color: #909399;
    }
  }

  .test-cases-table {
    margin-bottom: 10px;
  }

  .add-test-case-btn {
    display: flex;
    justify-content: center;
    margin-top: 10px;
  }
}

// 动画效果
.task-list-enter-active,
.task-list-leave-active {
  transition: all 0.3s ease;
}

.task-list-enter-from,
.task-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
</style>
